<template>
  <!-- 岗位调动 -->
  <div>
    <el-row :gutter="24">
      <el-col :span="2">
        <div class="grid-content ep-bg-purple">
          <el-button type="primary" plain @click="add" style="width: 100px;">
            <el-icon><Plus /></el-icon>添加
          </el-button>
        </div>
      </el-col>

      <el-col :span="1.5">
        <el-button type="primary" plain style="border: none;">
          导入
          <i class="el-icon-upload el-icon--right"></i>
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="primary" plain style="border: none;">
          导出
          <i class="el-icon-upload el-icon--right"></i>
        </el-button>
      </el-col>
      
      <el-col :span="2">
        <div class="grid-content ep-bg-purple">
          <el-button type="danger" plain @click="handleDelete">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </div>
      </el-col>
      
      <el-col :span="2">
        <div class="grid-content ep-bg-purple">
          <el-button type="success" plain @click="handleAudit" :disabled="selectedRows.length === 0">
            <el-icon><Check /></el-icon>审核
          </el-button>
        </div>
      </el-col>
      
      
      <el-col :span="8">
        <div class="grid-content ep-bg-purple"></div>
      </el-col>
      
      <el-col :span="4">
        <div class="grid-content ep-bg-purple-light">
          <el-input 
            v-model="keyword" 
            style="width: 180px" 
            size="large"
            placeholder="搜索"
            @keyup.enter="handleSearch">
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
        </div>
      </el-col>
      
      <el-col :span="1">
        <div class="grid-content ep-bg-purple-light">
          <a-tooltip content="筛选" position="bottom" background-color="rgb(52, 145, 250)" mini>
            <el-button size="default" @click="dialog = true">
              <el-icon><Filter /></el-icon>
            </el-button>
          </a-tooltip>
        </div>
      </el-col>

      <el-col :span="1">
        <div class="grid-content ep-bg-purple-light">
          <a-tooltip content="排序" position="bottom" background-color="rgb(52, 145, 250)" mini>
            <el-button size="default">
              <el-icon><Sort /></el-icon>
            </el-button>
          </a-tooltip>
        </div>
      </el-col>

      <el-col :span="2">
        <div class="grid-content ep-bg-purple-light">
          <a-tooltip content="刷新" position="bottom" background-color="rgb(52, 145, 250)" mini>
            <el-button size="default" @click="fetchData">
              <el-icon><Refresh /></el-icon>
            </el-button>
          </a-tooltip>
        </div>
      </el-col>
    </el-row>

    <el-table 
      :data="data" 
      border 
      style="width: 100%;" 
      @selection-change="handleSelectionChange"
      @cell-dblclick="handleRowClick">
      <el-table-column type="selection" fixed="left" label="选择" width="50" />
      <el-table-column prop="employeeName" label="员工姓名" width="120" />
      <el-table-column prop="employeeId" label="工号" width="120" />
      <el-table-column prop="auditStatus" label="审核状态" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.auditStatus === '已审核' ? 'success' : 'info'">
            {{ scope.row.auditStatus || '未审核' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="originalDepartment" label="原部门" width="120" />
      <el-table-column prop="originalPosition" label="原岗位" width="120" />
      <el-table-column prop="transferDepartmentName" label="调入部门" width="120" />
        <el-table-column prop="transferPositionName" label="调入岗位" width="120" />
      <el-table-column prop="employmentForm" label="聘用形式" width="120" />
      <el-table-column prop="entryDate" label="入职时间" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.entryDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="handlingHr" label="经办HR" width="120" />
      <el-table-column prop="transferReason" label="调动原因" width="120" />
      <el-table-column prop="newSalary" label="调动后薪资" width="120" />
      <el-table-column prop="completionTime" label="完成时间" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.completionTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="hrConfirmation" label="HR确认" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.hrConfirmation === '已确认' ? 'success' : 'info'">
            {{ scope.row.hrConfirmation || '未确认' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="applicationDate" label="申请时间" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.applicationDate) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="120">
        <template #default="scope">
          <el-button size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination 
      v-model:current-page="currentPage" 
      v-model:page-size="pageSize" 
      :page-sizes="[10, 20, 30, 40]"
      :disabled="disabled" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="total"
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange">
    </el-pagination>
    
    <el-dialog v-model="auditDialogVisible" title="确认审核" width="30%" center>
      <div style="text-align: center; padding: 20px 0;">
        <el-icon style="font-size: 40px; color: #409EFF; margin-bottom: 10px;">
          <Warning />
        </el-icon>
        <p>确定要审核通过选中的 {{ selectedRows.length }} 条岗位调动记录吗？</p>
        <p style="color: #999; font-size: 12px;">审核通过后将更新审核状态</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAudit" :loading="auditLoading">确认审核</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加页面 -->
    <el-dialog title="添加岗位调动" v-model="AddDisplay" fullscreen destroy-on-close @close="handleAddDialogClose">
      <OnboardingAddition @added="onJobTransferAdded" @close="handleAddDialogClose"></OnboardingAddition>
    </el-dialog>
    
    <!-- 详情页面 -->
    <el-dialog title="详细信息" v-model="detailVisible" fullscreen destroy-on-close @close="handleDetailClose">
      <hr />
      <JobTransferDetail 
        ref="detailRef" 
        @close="handleDetailClose">
      </JobTransferDetail>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%" center>
      <div style="text-align: center; padding: 20px 0;">
        <el-icon style="font-size: 40px; color: #F56C6C; margin-bottom: 10px;">
          <Warning />
        </el-icon>
        <p>确定要删除选中的 {{ selectedRows.length }} 条岗位调动记录吗？</p>
        <p style="color: #999; font-size: 12px;">此操作不可恢复，请谨慎操作</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete" :loading="deleteLoading">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!--筛选-->
    <el-drawer v-model="dialog" title="筛选" direction="rtl" class="demo-drawer">
      <div class="demo-drawer__content">
        <el-form :model="form" style="height: 600px;">
          <el-select v-model="Screening" placeholder="筛选" style="width: 360px" placement="bottom">
            <template #label="{ label, value }">
              <span style="font-weight: bold">{{ label }}</span>
            </template>
            <el-option v-for="item in FilterData" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取消</el-button>
          <el-button type="primary" :loading="loading" @click="onClick">
            {{ loading ? '提交中 ...' : '提交' }}
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import OnboardingAddition from '@/views/onboarding/jobTransfer/insert.vue'
import JobTransferDetail from '@/views/onboarding/jobTransfer/detailed.vue'
import axios from 'axios'

const AddDisplay = ref(false)
const loading = ref(false)
const dialog = ref(false)
const deleteDialogVisible = ref(false)
const deleteLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const disabled = ref(false)
const total = ref(0)
const data = ref([])
const keyword = ref('')
const selectedRows = ref([])
const detailVisible = ref(false)
const detailRef = ref(null)
const currentRow = ref(null)




// 查看详情
const handleViewDetail = (row) => {
  currentRow.value = row
  detailVisible.value = true
  nextTick(() => {
    if (detailRef.value && typeof detailRef.value.setJobTransferData === 'function') {
      detailRef.value.setJobTransferData(row)
    }
  })
}
const fetchData = async () => {
  try {
    const response = await axios.get('/api/jobtransfer/list', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        keyword: keyword.value,
        filter: Screening.value
      }
    })
    
    if (response.data.code === 200) {
      data.value = response.data.data.map(item => ({
        ...item,
        auditStatus: item.auditStatus || '未审核'
      }));
      total.value = response.data.total
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    ElMessage.error('获取数据失败: ' + (error.response?.data?.message || error.message))
    console.error(error)
  }
}

// 获取部门列表
const fetchDepartments = async () => {
  try {
    const response = await axios.get('/api/department/find');
    if (response.data.code === 200) {
      
      return response.data.data || [];
    }
  } catch (error) {
    console.error('获取部门数据失败:', error);
  }
  return [];
}

// 获取岗位列表
const fetchPositions = async () => {
  try {
    const response = await axios.get('/api/system/permission/post/find');
    if (response.data.code === 200) {
      return response.data.data || [];
    }
  } catch (error) {
    console.error('获取岗位数据失败:', error);
  }
  return [];
}
const handleRowClick = (row) => {
  handleViewDetail(row)
}

const auditDialogVisible = ref(false)
const auditLoading = ref(false)

const handleAudit = () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要审核的记录')
    return
  }
  auditDialogVisible.value = true
}

const confirmAudit = async () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning('没有选中的记录')
    return
  }
  
  auditLoading.value = true
  
  try {
    selectedRows.value.forEach(row => {
      const index = data.value.findIndex(item => item.employeeId === row.employeeId)
      if (index !== -1) {
        data.value[index].auditStatus = '已审核'
      }
    })
    
    ElMessage.success('审核成功')
    auditDialogVisible.value = false
    selectedRows.value = []
  } catch (error) {
    console.error('审核失败:', error)
    ElMessage.error('审核失败: ' + (error.response?.data?.message || error.message))
  } finally {
    auditLoading.value = false
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
const form = ref()
const Screening = ref('')
const FilterData = ref([
  { value: '', label: '全部' },
  { value: '已审核', label: '已审核' },
  { value: '未审核', label: '未审核' }
])

const onClick = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    dialog.value = false
    fetchData()
  }, 400)
}

const cancelForm = () => {
  loading.value = false
  dialog.value = false
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 点击删除按钮
const handleDelete = () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的记录')
    return
  }
  
  deleteDialogVisible.value = true
}
// 确认删除
const confirmDelete = async () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning('没有选中的记录')
    return
  }
  
  deleteLoading.value = true
  
  try {
    // 使用 employeeId 而不是 id
    const ids = selectedRows.value.map(row => row.employeeId)
    
    // 调用删除接口
    const response = await axios.delete('/api/jobtransfer/delete', {
      data: { ids: ids }
    })
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      deleteDialogVisible.value = false
      fetchData()
    } else {
      ElMessage.error('删除失败: ' + response.data.message)
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
  } finally {
    deleteLoading.value = false
  }
}

// 打开添加对话框
const add = () => {
  AddDisplay.value = true
}

// 岗位调动添加成功后的回调
const onJobTransferAdded = async () => {
  AddDisplay.value = false
  await fetchData()
}

// 处理添加对话框关闭
const handleAddDialogClose = () => {
  AddDisplay.value = false
}

// 处理详情对话框关闭
const handleDetailClose = () => {
  detailVisible.value = false
}

// 处理分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 处理当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 搜索功能
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped></style>